package com.victualler.core.common.filter;


import com.victualler.core.common.web.LoginController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Aouthor Guoshichang
 * @Date 13:52 on 2018/4/8.
 * @Function 统一拦截接口响应相关的过滤器
 */
@WebFilter(filterName = "permissionFilter", urlPatterns = {"/*"})
public class PermissionFilter implements Filter {
	/**
	 * 日志记录
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(PermissionFilter.class); 
	/*
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
	@Override
	public void init(FilterConfig config) throws ServletException {
		// filter不能通过注解获取spring的Bean实例,此处使用servlet上下文凡是获得配置信息的bean实例
		// weblogic通过上下文获取有问题，暂时改为直接读取文件的形式


	}

	/*
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
     * javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest requestWrapper = (HttpServletRequest) request;
		HttpServletResponse responseWrapper = (HttpServletResponse) response;

		//取请求内容
		System.out.println( requestWrapper.getRequestURL()+" 请求：  "+requestWrapper.getSession().getId() );
		String reqUrl = requestWrapper.getRequestURI();
		if(canIgnore(requestWrapper)){
			chain.doFilter(requestWrapper, responseWrapper);
			return ;
		}
		Object user = requestWrapper.getSession().getAttribute(LoginController.userSessionKey);
		//加入用户 或微信用户的非空判断
		if(user == null && requestWrapper.getHeader("openId") == null){
			responseWrapper.sendRedirect(requestWrapper.getContextPath()+"/login");
			return ;
		}else{
			chain.doFilter(requestWrapper, responseWrapper);
		}
	}
	/**
	 * @Aouthor Guoshichang
	 * @Date 11:37 on 2018/6/13.
	 * @param request
	 * @Function  过滤静态资源
	 */

	private boolean canIgnore(HttpServletRequest request){
		if(request.getServletPath().startsWith("/favicon.ico") ||
		   request.getServletPath().startsWith("/css") ||
		   request.getServletPath().startsWith("/img") ||
		   request.getServletPath().startsWith("/js") ||
		   request.getServletPath().startsWith("/config/img/loadImg") ||
		   request.getServletPath().startsWith("/session") ||
		   request.getServletPath().startsWith("/product/goods/getGoodsByRequestDtoByIndex") || //放开此请求用于展示首页信息
		   request.getServletPath().startsWith("/login")){
			return true;
		}

		return false;
	}
	
	/*
     * @see javax.servlet.Filter#destroy()
     */
	@Override
	public void destroy() {
	}


}
